package controllers

import (
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
	"path/filepath"
	"patient/models"
	"strconv"
	"strings"
)

type PatientController struct {
	beego.Controller
}

// 上传
func (c *PatientController) Upload() {
	file, header, err := c.GetFile("img")
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "请上传文件",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	defer file.Close()
	if header.Size > 2*1024*1024 {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "文件过大,请重新上传",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	ext := map[string]bool{
		".png":  true,
		".jpeg": true,
	}
	suffix := strings.ToLower(filepath.Ext(header.Filename))
	if !ext[suffix] {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "文件类型错误",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	path := "static/img/" + header.Filename
	err = c.SaveToFile("img", path)
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "上传失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		imgUrl := "http://127.0.0.1:8080/" + path
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "上传成功",
			Data: imgUrl,
		}
		c.ServeJSON()
		return
	}
}

// 添加
func (c *PatientController) Add() {
	name := c.GetString("name")
	age, _ := c.GetInt("age")
	sex := c.GetString("sex")
	tel := c.GetString("tel")
	text := c.GetString("text")
	img := c.GetString("img")
	patient := models.Patient{
		Name: name,
		Age:  age,
		Sex:  sex,
		Tel:  tel,
		Text: text,
		Img:  img,
	}
	err := models.DB.Model(&models.Patient{}).Create(&patient).Error
	if name == "" || sex == "" || tel == "" || text == "" || img == "" {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "字段信息不能为空",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	if age <= 0 {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "字段信息不能为空",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "添加成功",
			Data: patient,
		}
		c.ServeJSON()
	}
}

// 列表
func (c *PatientController) List() {
	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 5)
	query := models.DB.Model(&models.Patient{})
	pageData := make(map[string]interface{})
	name := c.GetString("name")
	key := "patient" + strconv.Itoa(page) + "-" + name
	val, err := models.Rdb.Get(key).Result()
	if name != "" {
		query = query.Where("name like ?", "%"+name+"%")
	}
	if err != nil {
		var count int64
		query.Count(&count)
		var patient []models.Patient
		offset := (page - 1) * size
		err = query.Offset(offset).Limit(size).Find(&patient).Error
		if err != nil {
			c.Data["json"] = JsonR{
				Code: 500,
				Msg:  "查询失败",
				Data: nil,
			}
			c.ServeJSON()
			return
		} else {
			pageData["count"] = count
			//pageData["page"] = page
			pageData["patient"] = patient
			marshal, _ := json.Marshal(&pageData)
			value := string(marshal)
			models.Rdb.Set(key, value, 0)
			c.Data["json"] = JsonR{
				Code: 200,
				Msg:  "查询成功-mysql",
				Data: pageData,
			}
			c.ServeJSON()
		}
	} else {
		json.Unmarshal([]byte(val), &pageData)
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "查询成功-redis",
			Data: pageData,
		}
		c.ServeJSON()
	}

}

// 详情
func (c *PatientController) Info() {
	id, _ := c.GetInt("id")
	var patient models.Patient
	key := "patient" + strconv.Itoa(id)
	val, err := models.Rdb.Get(key).Result()
	RankKey := "patient-rank"
	if err != nil {
		err = models.DB.Model(&models.Patient{}).Where("ID=?", id).First(&patient).Error
		if err != nil {
			c.Data["json"] = JsonR{
				Code: 500,
				Msg:  "详情展示失败",
				Data: nil,
			}
			c.ServeJSON()
			return
		} else {
			marshal, _ := json.Marshal(&patient)
			value := string(marshal)
			models.Rdb.Set(key, value, 0)
			models.Rdb.ZIncrBy(RankKey, 1, patient.Name)
			c.Data["json"] = JsonR{
				Code: 200,
				Msg:  "详情展示成功-mysql",
				Data: patient,
			}
			c.ServeJSON()
		}
	} else {
		json.Unmarshal([]byte(val), &patient)
		models.Rdb.ZIncrBy(RankKey, 1, patient.Name)
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "详情展示成功-redis",
			Data: patient,
		}
		c.ServeJSON()
	}

}

// 排行榜
func (c *PatientController) Rank() {
	key := "patient-rank"
	nums := models.Rdb.ZCard(key).Val()
	ranks, err := models.Rdb.ZRangeWithScores(key, 0, nums-1).Result()
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "查询失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "查询成功",
			Data: ranks,
		}
		c.ServeJSON()
	}
}

// 修改状态
func (c *PatientController) Up() {
	id, _ := c.GetInt("id")
	sex := c.GetString("sex")
	patient := models.Patient{
		Sex: sex,
	}
	err := models.DB.Model(&models.Patient{}).Where("ID=?", id).Updates(&patient).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "修改失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "修改成功",
			Data: patient,
		}
		c.ServeJSON()
	}
}
